package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.model.behavior.dtos.ReadBehaviorDTO;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApReadBehavior;
import com.heima.model.common.constants.article.HotArticleConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.exception.CustException;
import com.heima.model.mess.app.NewBehaviorDTO;
import com.heima.model.threadLocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import com.mongodb.client.result.UpdateResult;
import com.sun.org.apache.bcel.internal.generic.NEW;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.flyway.FlywayDataSource;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Date;

@Slf4j
@Service
public class ApReadBehaviorServiceImpl implements ApReadBehaviorService {
    @Autowired
    private ApBehaviorEntryServiceImpl apBehaviorEntryService;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public ResponseResult readBehavior(ReadBehaviorDTO dto) {
        //1. 校验参数 文章id必须传 注解实现
        //2. 根据登录用户id 或 设备id查询行为实体数据(阅读操作可不登录)
        ApUser user = AppThreadLocalUtils.getUser();
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());
        if (apBehaviorEntry == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "行为实体对象不存在或者创建失败!");
        }
        //3. 判断阅读行为是否存在
        Query query = Query.query(Criteria.where("articleId").is(dto.getArticleId()).and("entryId").is(apBehaviorEntry.getId()));
        ApReadBehavior apReadBehavior = mongoTemplate.findOne(query, ApReadBehavior.class);
        if (apReadBehavior != null) {
            //4. 存在  将阅读行为的count字段加1 并修改
            int count = apReadBehavior.getCount().intValue();
            count += 1;
            Update update = new Update();
            update.set("count", count);
            update.set("updatedTime", new Date());
            UpdateResult updateResult = mongoTemplate.updateFirst(query, update, ApReadBehavior.class);
            System.out.println(updateResult);
        } else {
            //5. 不存在  创建阅读行为 并初始化count字段值为 1
            ApReadBehavior newReadBehavior = new ApReadBehavior();
            newReadBehavior.setCount((short) 1);
            newReadBehavior.setCreatedTime(new Date());
            newReadBehavior.setArticleId(dto.getArticleId());
            newReadBehavior.setEntryId(apBehaviorEntry.getId());
            ApReadBehavior save = mongoTemplate.save(newReadBehavior);
            System.out.println(save);
        }
        // 发送新行为消息
        NewBehaviorDTO newBehavior = new NewBehaviorDTO();
        newBehavior.setAdd(1);
        newBehavior.setType(NewBehaviorDTO.BehaviorType.VIEWS);
        newBehavior.setArticleId(dto.getArticleId());
        rabbitTemplate.convertAndSend(HotArticleConstants.HOT_ARTICLE_SCORE_BEHAVIOR_QUEUE, JSON.toJSONString(newBehavior));
        log.info("成功发送 文章阅读行为消息,消息内容: {}", newBehavior);
        return ResponseResult.okResult();
    }
}
